package com.xmqian.app.common.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.coszero.utilslibrary.utils.LogX;
import com.xmqian.app.R;
import com.xmqian.app.common.utils.umeng.UMengAnalyticsUtils;
import com.xmqian.app.common.widget.MyToolBar;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Desc： 每个项目自定义的父类
 * <p>
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/6/4 19:48
 */
public abstract class MyBaseFragment extends Fragment {
    protected Context context;
    protected String TAG = this.getClass().getSimpleName();
    private Unbinder unbinder;//用来重置绑定
    @Nullable
    @BindView(R.id.my_toolbar)
    MyToolBar myToolBar;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            View layout = inflater.inflate(getLayoutResource(), container, false);
            unbinder = ButterKnife.bind(this, layout);
            return layout;
        } catch (Exception e) {
            String errorMsg = "布局使用异常，移除类：" + this.getClass().getSimpleName() + " 异常布局ID:" + getLayoutResource() +
                    " 异常信息：" + e.toString();
            LogX.e("###BaseFragment", errorMsg);
            new Throwable(errorMsg);
        }
        return null;
    }

    /*返回布局ID*/
    public abstract int getLayoutResource();


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Nullable
    public MyToolBar getMyToolBar() {
        return myToolBar;
    }

    public void setTitle(String title) {
        if (myToolBar != null) {
            myToolBar.setMainTitle(title);
        }
    }

    protected abstract void initView();

    @Override
    public void onResume() {
        super.onResume();
        UMengAnalyticsUtils.onResumeToFragment(TAG);
    }

    @Override
    public void onPause() {
        UMengAnalyticsUtils.onPauseToFragment(TAG);
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroyView();
    }
}
